package org.ru.mse10.cvis.upload;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;

import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.service.MailService;
import org.ru.mse10.cvis.service.UserService;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class UserCSVRowHandler.
 */
public class UserCSVRowHandler extends CommonHandler<String> {

	/** The context. */
	private final FacesContext context = FacesContext.getCurrentInstance();

	/** The bundle. */
	private final ResourceBundle bundle = context.getApplication()
			.getResourceBundle(context, "message");

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.ru.mse10.cvis.upload.CommonHandler#handle(java.lang.Object)
	 */
	@Override
	public void handle(String row) {
		System.err.println(row.toString());
		String[] split = row.split("\\s*,\\s*");
		if (split == null || split.length == 0 || split.length != 2) {
			throw new RuntimeException("Invalid row data.");
		}
		User user = new User();
		user.setEmail(split[0]);
		user.setRole(getRole(split[1]));

		try {
			UserService userService = CommonUtil
					.lookupService(UserService.class);
			MailService mailService = CommonUtil
					.lookupService(MailService.class);
			if (userService.isExistingUserEmail(user.getEmail())) {
				FacesContext.getCurrentInstance().addMessage(
						"uploadForm",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle
								.getString("errorUploadFileMail"), null));
			} else {
				String password = setPasswordToUser(user);
				userService.saveInNewTx(user);
				String subject = "You have been registered in CVIS!";
				String mailText = "You have been registered in CVIS!\nTo access the system use the following credentials:\nUsername: "
						+ user.getEmail() + "\nPassword: " + password;
				mailService.sendUserMail(password, user.getEmail(), subject,
						mailText);
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
}
